import React, { useEffect, useState, useRef } from 'react';
import { Layout, FloatButton, Drawer, message, Spin } from 'antd';
import { FileTextOutlined, UploadOutlined } from '@ant-design/icons';
import Sidebar from './components/Sidebar';
import ProductSelector from './components/ProductSelector';
import ProductComparison from './components/ProductComparison';
import ExcelUploader from './components/ExcelUploader';
import ImageTest from './components/ImageTest';
import { ProductProvider, useProduct } from './context/ProductContext';
import { loadLocalExcelFiles } from './utils/excelParser';
import './App.css';

const { Content } = Layout;

const AppContent: React.FC = () => {
  const { state, dispatch } = useProduct();
  const { selectedProducts, currentView, loading } = state;
  const [showUploader, setShowUploader] = useState(false);
  const hasLoadedRef = useRef(false); // 防止重复加载

  // 在组件挂载时自动加载Excel文件
  useEffect(() => {
    // 如果已经加载过，直接返回
    if (hasLoadedRef.current) {
      return;
    }

    const loadExcelData = async () => {
      try {
        hasLoadedRef.current = true; // 标记为已加载
        dispatch({ type: 'SET_LOADING', payload: true });
        
        console.log('🚀 开始加载Excel数据...');
        const categories = await loadLocalExcelFiles();
        dispatch({ type: 'SET_CATEGORIES', payload: categories });
        
        if (categories.length > 0) {
          console.log('✅ 加载成功，显示成功消息');
          message.success(`成功加载 ${categories.length} 个产品分类的数据`);
        } else {
          console.log('ℹ️ 没有找到预设数据');
          message.info('没有找到预设数据，请上传Excel文件开始使用', 3);
        }
      } catch (error) {
        console.error('❌ 加载Excel数据失败:', error);
        dispatch({ type: 'SET_ERROR', payload: '加载数据失败' });
        hasLoadedRef.current = false; // 失败时重置，允许重试
      }
    };

    loadExcelData();
  }, []); // 移除 dispatch 依赖，只在组件挂载时执行一次

  // 如果正在加载，显示加载状态（由Sidebar组件处理）
  if (loading) {
    return null; // 让Sidebar处理加载状态显示
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Layout.Sider width={280} style={{ background: '#001529' }}>
        <Sidebar />
      </Layout.Sider>
      <Layout>
        <Content style={{ margin: 0, background: '#fff' }}>
          {window.location.href.includes('test') ? (
            <ImageTest />
          ) : (
            currentView === 'selector' ? <ProductSelector /> : <ProductComparison />
          )}
        </Content>
      </Layout>

      {/* 浮动按钮组 */}
      <FloatButton.Group
        trigger="hover"
        type="primary"
        style={{ right: 24 }}
        icon={<FileTextOutlined />}
        tooltip="产品工具"
      >
        <FloatButton
          icon={<FileTextOutlined />}
          tooltip="产品对比"
          onClick={() => {
            if (selectedProducts.length === 0) {
              message.warning('请先选择要对比的产品');
              return;
            }
            dispatch({ type: 'SET_VIEW', payload: currentView === 'selector' ? 'comparison' : 'selector' });
          }}
        />
        <FloatButton
          icon={<UploadOutlined />}
          tooltip="Excel文件管理"
          onClick={() => setShowUploader(true)}
        />
      </FloatButton.Group>

      {/* Excel上传抽屉 */}
      <Drawer
        title="Excel文件管理"
        placement="right"
        onClose={() => setShowUploader(false)}
        open={showUploader}
        width={600}
      >
        <ExcelUploader />
      </Drawer>
    </Layout>
  );
};

const App: React.FC = () => {
  return (
    <ProductProvider>
      <AppContent />
    </ProductProvider>
  );
};

export default App;
